<template>
  <div class="p-2">
    <div v-if="!dialog.visible">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="商品编号" prop="productNo">
                <el-input v-model="queryParams.productNo" placeholder="请输入商品编号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">{{$t('button.search')}}</el-button>
                <el-button icon="Refresh" @click="resetQuery">{{$t('button.reset')}}</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>

      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-hasPermi="['shopping:product:add']" type="primary" icon="Plus" @click="handleAdd">{{$t('button.add')}}</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['shopping:product:edit']" type="success" icon="Edit" :disabled="single" @click="handleUpdate()">{{$t('button.update')}}</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['shopping:product:remove']" type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()">{{$t('button.delete')}}</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['shopping:product:export']" type="warning" icon="Download" @click="handleExport">{{$t('button.export')}}</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
          </el-row>
        </template>

        <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品编号" align="center" prop="productNo" />
          <el-table-column label="商品名称" align="center" prop="productName" />
          <el-table-column label="商品图片" align="center" prop="imageUrl" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column label="商品简介" align="center" prop="storeInfo" />
          <el-table-column label="关键字" align="center" prop="keyword" />
          <el-table-column label="展示价格" align="center" prop="labelPrice" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="销量" align="center" prop="sales" />
          <!--        <el-table-column label="是否限购 0 - 不限购  1 - 限购" align="center" prop="isLimit" />-->
          <!--        <el-table-column label="限购数量" align="center" prop="limitCount" />-->
          <el-table-column label="状态" align="center" prop="isShow" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip :content="$t('button.update')" placement="top">
                <el-button v-hasPermi="['shopping:product:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip :content="$t('button.delete')" placement="top">
                <el-button v-hasPermi="['shopping:product:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      </el-card>
    </div>

    <!-- 添加或修改商品对话框 -->
    <div v-if="dialog.visible" style="width: 80%; margin-left: 20%">
      <el-form ref="productFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input ref="storeName" v-model="form.productName" size="default" placeholder="请输入 商品 / 服务 名称" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品简介" prop="storeInfo" style="width: 50%">
              <el-input v-model="form.storeInfo" type="textarea" size="default" placeholder="请输入商品简介" :rows="3" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="关键字" prop="keyword" style="width: 50%">
              <el-input v-model="form.keyword" size="default" placeholder="请输入关键字" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item :label="'预览图片'">
              <single-pic
                :imgList="form.productImgs"
                type="image"
                :upload-type="1"
                :num="1"
                :width="150"
                :height="150"
                @handle-checked="chooseGoodsImg"
              />
              <single-pic type="image" :upload-type="1" :num="1" :width="150" :height="150" @handle-checked="chooseGoodsImg" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="轮播图">
              <single-pic
                :imgList="form.productImgLunbos"
                type="image"
                :upload-type="1"
                :num="9"
                :width="150"
                :height="150"
                @handle-checked="chooseGoodsLunboImg"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="展示价格" prop="labelPrice" style="width: 100%">
              <el-input v-model="form.labelPrice" size="default" placeholder="请输入展示价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isShow">
              <el-radio-group v-model="form.isShow" size="default">
                <el-radio :value="1" :label="1">上架</el-radio>
                <el-radio :value="0" :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="是否限购" prop="isLimit">
              <el-radio-group v-model="form.isLimit" size="default">
                <el-radio :value="0" :label="0">不限购</el-radio>
                <el-radio :value="1" :label="1">限购</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="form.isLimit === 1" :span="6">
            <el-form-item label="限购数量" prop="limitCount">
              <el-input v-model="form.limitCount" type="number" size="default" placeholder="请输入限购数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品规格" prop="specType">
              <el-radio-group v-model="form.specType" size="default">
                <el-radio :value="0" :label="0">单规格</el-radio>
                <el-radio :value="1" :label="1">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品分类" prop="cateChildId" style="width: 35%">
              <el-select v-model="form.cateChildId" style="width: 100%" size="default" @change="confirm()">
                <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id">
                  {{ item.typeName }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.specType === 1">
          <!--          <el-col :span="24" class="noForm">-->

          <el-col :span="24">
            <el-form-item label="选择规格：" prop="ruleId" style="width: 35%">
              <el-select v-model="form.ruleId" style="width: 100%" size="default" placeholder="请选择规格" @change="confirm">
                <el-option v-for="rule in ruleListOptions" :key="rule.id" :label="rule.ruleName" :value="rule.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item v-if="attrs.length !== 0">
              <div v-for="(item, index) in attrs" :key="index">
                <div class="acea-row row-middle">
                  <span class="mr5">{{ item.value }}</span>
                  <i class="el-icon-circle-close" @click="handleRemoveRole(index)"></i>
                </div>
                <div class="rulesBox">
                  <el-tag
                    v-for="(j, indexn) in item.detail"
                    :key="indexn"
                    type="dot"
                    closable
                    color="primary"
                    class="mr20"
                    :name="j"
                    @close="handleRemove2(item.detail, indexn)"
                    >{{ j }}</el-tag
                  >
                  <el-input v-model="item.detail.attrsVal" placeholder="请输入属性名称" style="width: 200px" size="default">
                    <template #append>
                      <el-button size="default" type="primary" @click="createAttr(item.detail.attrsVal, index)">添加</el-button>
                    </template>
                  </el-input>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col v-if="createBtn" :span="24">
            <el-form-item>
              <el-button type="primary" icon="md-add" class="mr15" size="default" @click="addBtn">添加新规格</el-button>
              <el-button type="success" size="default" @click="generate(0)">立即生成</el-button>
              <el-button type="warning" size="default" @click="generate(1)">重新生成</el-button>
            </el-form-item>
          </el-col>

          <el-col v-if="showInput" :span="24">
            <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
              <el-form-item label="规格：">
                <el-input v-model="formDynamic.attrsName" placeholder="请输入规格" size="default" />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
              <el-form-item label="规格值：">
                <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值" size="default" />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
              <el-button type="primary" size="default" @click="createAttrName">确定</el-button>
              <el-button type="danger" size="default" @click="offAttrName">取消</el-button>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <!-- 多规格设置-->
          <el-col v-if="manyFormValidate !== undefined && manyFormValidate.length && form.header.length !== 0 && attrs.length !== 0">
            <!-- 多规格表格-->
            <el-col :span="24">
              <el-form-item label="商品属性：" class="labeltop">
                <el-table :data="manyFormValidate" size="default" style="width: 50%">
                  <el-table-column
                    v-for="(item, index) in form.header"
                    :key="index"
                    type="myindex"
                    :label="item.title"
                    :property="item.slot"
                    align="center"
                  >
                    <template #default="scope">
                      <div v-if="scope.column != undefined && scope.column.property.indexOf('value') != -1">
                        {{ scope.row[scope.column.property] }}
                      </div>
                      <div v-else-if="scope.column != undefined && scope.column.property === 'action'">
                        <a @click="delAttrTable(scope.$index)">{{$t('button.delete')}}</a>
                      </div>
                      <div v-else>
                        <el-input v-model="scope.row[scope.column.property]" size="default" />
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-col>
          <!--          </el-col>-->
        </el-row>
        <el-row>
          <!-- 单规格表格-->
          <el-col v-if="form.specType === 0" :xl="23" :lg="24" :md="24" :sm="24" :xs="24">
            <el-form-item>
              <el-table :data="oneFormValidate" size="default" style="width: 50%">
                <el-table-column prop="price" label="售价" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.price" type="text" size="default" />
                  </template>
                </el-table-column>
                <el-table-column prop="otPrice" label="原价" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.otPrice" type="text" size="default" />
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.stock" type="text" size="default" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="排序" prop="sort" style="width: 100%">
              <el-input v-model="form.sort" type="number" placeholder="请输入排序" size="default" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前销量" prop="sales" style="width: 50%">
              <el-input v-model="form.sales" type="number" placeholder="请输入当前销量" size="default" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="购买须知" prop="buyingTips">
              <editor v-model="form.buyingTips" :min-height="192" size="default" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="产品描述" prop="description">
              <editor v-model="form.description" :min-height="192" size="default" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="Product" lang="ts">
import { listProduct, getProduct, delProduct, addProduct, updateProduct, isFormatAttr } from '@/api/shopping/product';
import { ProductVO, ProductQuery, ProductForm } from '@/api/shopping/product/types';
import { listNoPageRule } from '@/api/shopping/product/rule';
import { listType, getType, delType, addType, updateType } from '@/api/shopping/product/type';

import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();

import SinglePic from '@/components/SingleMaterial/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const oneFormValidate = ref([
  {
    price: 0,
    otPrice: 0,
    stock: 9999
  }
]);
// 规格数据
const formDynamic = ref({
  attrsName: '',
  attrsVal: ''
});
const showInput = ref(false);
const createBtn = ref(false);

const manyFormValidate = ref([]);
const ruleListOptions = ref([]);

const splits = ref([]);
const attrs = ref([]);
const typeList = ref([]);

const productStateOption = ref([]);
const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProductForm = {
  id: undefined,
  productNo: undefined,
  merId: undefined,
  productName: undefined,
  image: undefined,
  sliderImage: undefined,
  storeInfo: undefined,
  keyword: undefined,
  cateId: undefined,
  cateChildId: undefined,
  ruleId: undefined,
  voucherId: undefined,
  labelPrice: undefined,
  price: undefined,
  isVip: undefined,
  vipPrice: undefined,
  otPrice: undefined,
  postage: undefined,
  unitName: undefined,
  sort: undefined,
  sales: undefined,
  stock: undefined,
  isSale: 1,
  isLimit: undefined,
  limitCount: undefined,
  isShow: undefined,
  isHot: 0,
  isBenefit: 0,
  isBest: 0,
  isNew: 0,
  isCoupon: undefined,
  description: undefined,
  isPostage: undefined,
  isDel: 0,
  cost: undefined,
  isGood: 0,
  ficti: undefined,
  browse: undefined,
  isSub: undefined,
  subType: undefined,
  splitMoney: undefined,
  tempId: undefined,
  specType: undefined,
  splitType: undefined,
  splitTypeId: undefined,
  proprietorRate: undefined,
  propertyRate: undefined,
  platformRate: undefined,
  qrCode: undefined,
  buyingTips: undefined,
  header: [],
  productImgs: [],
  productImgLunbos: [],
  sliderImagePath: undefined
};
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: 0,
    productNo: undefined,
    merId: undefined,
    productName: undefined,
    image: undefined,
    sliderImage: undefined,
    storeInfo: undefined,
    keyword: undefined,
    cateId: undefined,
    cateChildId: undefined,
    ruleId: undefined,
    voucherId: undefined,
    labelPrice: undefined,
    price: undefined,
    isVip: undefined,
    vipPrice: undefined,
    otPrice: undefined,
    postage: undefined,
    unitName: undefined,
    sort: undefined,
    sales: undefined,
    stock: undefined,
    isSale: undefined,
    isLimit: undefined,
    limitCount: undefined,
    isShow: undefined,
    isHot: undefined,
    isBenefit: undefined,
    isBest: undefined,
    isNew: undefined,
    isCoupon: undefined,
    description: undefined,
    isPostage: undefined,
    isDel: undefined,
    cost: undefined,
    isGood: undefined,
    ficti: undefined,
    browse: undefined,
    isSub: undefined,
    subType: undefined,
    splitMoney: undefined,
    tempId: undefined,
    specType: undefined,
    splitType: undefined,
    splitTypeId: undefined,
    proprietorRate: undefined,
    propertyRate: undefined,
    platformRate: undefined,
    qrCode: undefined,
    buyingTips: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '商品id不能为空', trigger: 'blur' }],
    productNo: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
    merId: [{ required: true, message: '服务商家id不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
    image: [{ required: true, message: '商品图片不能为空', trigger: 'blur' }],
    sliderImage: [{ required: true, message: '轮播图不能为空', trigger: 'blur' }],
    storeInfo: [{ required: true, message: '商品简介不能为空', trigger: 'blur' }],
    keyword: [{ required: true, message: '关键字不能为空', trigger: 'blur' }],
    cateId: [{ required: true, message: '分类id不能为空', trigger: 'blur' }],
    cateChildId: [{ required: true, message: '子分类id不能为空', trigger: 'blur' }],
    ruleId: [{ required: true, message: '规格id不能为空', trigger: 'blur' }],
    voucherId: [{ required: true, message: '关联的消费券id不能为空', trigger: 'blur' }],
    labelPrice: [{ required: true, message: '展示价格不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '商品价格不能为空', trigger: 'blur' }],
    isVip: [{ required: true, message: '是否是会员特价   0 - 不是  1 - 是不能为空', trigger: 'blur' }],
    vipPrice: [{ required: true, message: '会员价格不能为空', trigger: 'blur' }],
    otPrice: [{ required: true, message: '市场价不能为空', trigger: 'blur' }],
    postage: [{ required: true, message: '邮费不能为空', trigger: 'blur' }],
    unitName: [{ required: true, message: '单位名不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
    sales: [{ required: true, message: '销量不能为空', trigger: 'blur' }],
    stock: [{ required: true, message: '库存不能为空', trigger: 'blur' }],
    isSale: [{ required: true, message: '是否是销售类型的商品或服务  0 - 咨询类型 1 - 销售类型不能为空', trigger: 'blur' }],
    isLimit: [{ required: true, message: '是否限购 0 - 不限购  1 - 限购不能为空', trigger: 'blur' }],
    limitCount: [{ required: true, message: '限购数量不能为空', trigger: 'blur' }],
    isShow: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    isHot: [{ required: true, message: '是否热卖不能为空', trigger: 'blur' }],
    isBenefit: [{ required: true, message: '是否优惠不能为空', trigger: 'blur' }],
    isBest: [{ required: true, message: '是否精品不能为空', trigger: 'blur' }],
    isNew: [{ required: true, message: '是否新品不能为空', trigger: 'blur' }],
    isCoupon: [{ required: true, message: '是否是折扣券不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '产品描述不能为空', trigger: 'blur' }],
    isPostage: [{ required: true, message: '是否包邮不能为空', trigger: 'blur' }],
    isDel: [{ required: true, message: '是否删除不能为空', trigger: 'blur' }],
    cost: [{ required: true, message: '成本价不能为空', trigger: 'blur' }],
    isGood: [{ required: true, message: '是否优品推荐不能为空', trigger: 'blur' }],
    ficti: [{ required: true, message: '虚拟销量不能为空', trigger: 'blur' }],
    browse: [{ required: true, message: '浏览量不能为空', trigger: 'blur' }],
    isSub: [{ required: true, message: '是否单独分佣 0 - 否 1 - 是不能为空', trigger: 'blur' }],
    subType: [{ required: true, message: '分佣方式  0 - 按固定金额  1 - 按售价的比例不能为空', trigger: 'change' }],
    splitMoney: [{ required: true, message: '拿出来的分成总额不能为空', trigger: 'blur' }],
    tempId: [{ required: true, message: '运费模板ID不能为空', trigger: 'blur' }],
    specType: [{ required: true, message: '规格 0单 1多不能为空', trigger: 'change' }],
    splitType: [{ required: true, message: '分成类型code不能为空', trigger: 'change' }],
    splitTypeId: [{ required: true, message: '分成类型id不能为空', trigger: 'blur' }],
    proprietorRate: [{ required: true, message: '业主分成比例不能为空', trigger: 'blur' }],
    propertyRate: [{ required: true, message: '物业公司分成比例不能为空', trigger: 'blur' }],
    platformRate: [{ required: true, message: '平台分成比例不能为空', trigger: 'blur' }],
    qrCode: [{ required: true, message: '产品二维码不能为空', trigger: 'blur' }],
    buyingTips: [{ required: true, message: '购买须知不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/**
 *  获取商品分类
 */
const getProductTypeChildList = async () => {
  const res = await listType(queryParams.value);
  typeList.value = res.rows;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  productFormRef.value?.resetFields();
};

// 添加按钮
const addBtn = () => {
  clearAttr();
  createBtn.value = false;
  showInput.value = true;
};

/**
 *  选择规格
 * @param val
 */
const confirm = (val) => {
  console.log('confirm', val);
  for (var index in ruleListOptions.value) {
    console.log('that.ruleListOptions[index]', ruleListOptions.value[index]);
    if (ruleListOptions.value[index].id === val) {
      attrs.value = ruleListOptions.value[index].ruleValueArray;
      form.value.ruleId = ruleListOptions.value[index].id;
      createBtn.value = true;
    }
  }
  console.log('that.form.ruleId', form.value.ruleId);
  getRuleList(val);
};

const getRuleList = (ruleId) => {
  listNoPageRule(ruleId).then((res) => {
    ruleListOptions.value = res.data;
  });
};

/**
 *  选择商品图片
 * @param data
 */
const chooseGoodsImg = (data) => {
  console.log('product chooseGoodsImg', data);
  form.value.productImgs = [];
  if (data.length > 0) {
    form.value.imagePath = data[0].imgUrl;
    form.value.image = data[0].url;

    var newImg = {
      productId: form.value.id,
      imgUrl: data[0].url,
      imgUrlPath: data[0].imgUrl
    };
    form.value.productImgs.push(newImg);
  }
  console.log('form.value.productImgs', form.value.productImgs);
};

/**
 *  选择商品轮播图片
 * @param data
 */
const chooseGoodsLunboImg = (data) => {
  console.log('product chooseGoodsLunboImg', data);
  if (form.value.productImgLunbos == undefined) {
    form.value.productImgLunbos = [];
  }

  form.value.sliderImage = '';
  form.value.sliderImagePath = '';
  var imgUrlArray = data.value;
  // var imgUrlArrayPath = data.imgUrl;
  for (var index in imgUrlArray) {
    var imgUrl = imgUrlArray[index].imgUrl; // 全地址
    var url = imgUrlArray[index].url; // 数据库保存的地址

    form.value.sliderImage += url + ',';
    form.value.sliderImagePath += imgUrl + ',';
  }

  var newImg = {
    productId: form.value.id,
    imgUrl: url,
    imgUrlPath: imgUrl
  };
  form.value.productImgLunbos.push(newImg);
  form.value.sliderImage = form.value.sliderImage.substring(0, form.value.sliderImage.length - 1);
  form.value.sliderImagePath = form.value.sliderImagePath.substring(0, form.value.sliderImagePath.length - 1);
  console.log('sliderImageArray', form.value.sliderImageArray);
  console.log('productImgLunbos', form.value.productImgLunbos);
};

/**
 *  删除图片
 * @param data
 */
const removeImg = (data) => {
  console.log('removeImg', data);
  console.log('productImgLunbos', form.value.productImgLunbos);
  form.value.sliderImagePath = '';
  var imgUrlArray = data.imgList;
  for (var index in imgUrlArray) {
    form.value.sliderImagePath += imgUrlArray[index].url + ',';
  }
  form.value.sliderImagePath = form.value.sliderImagePath.substring(0, form.value.sliderImagePath.length - 1);
  //删除的 索引
  var index = data.index;
  form.value.productImgLunbos.splice(index, 1);
};

// 取消
const offAttrName = () => {
  showInput.value = false;
  createBtn.value = true;
};

const clearAttr = () => {
  formDynamic.value.attrsName = '';
  formDynamic.value.attrsVal = '';
};

// 立即生成
const generate = (isReset) => {
  console.log('generate  this.attrs', attrs.value);
  if (form.value.id === undefined) {
    form.value.id = 0;
  }
  isFormatAttr(form.value.id, { attrs: attrs.value }, isReset)
    .then((res) => {
      console.log('generate  isFormatAttr', res);
      manyFormValidate.value = res.data.value;
      let headerdel = {
        title: '操作',
        slot: 'action',
        fixed: 'right',
        width: 220
      };
      res.data.header.push(headerdel);
      console.log(' generate  res.data.header', res.data.header);
      form.value.header = res.data.header;
      // console.log('generate  form.value.header',form.value.header);
      let header = res.data.header;
      // console.log(' generate  header',header);
      header.pop();
      // console.log(' generate  manyFormValidate',manyFormValidate);
    })
    .catch((res) => {});
};

// 删除规格
const handleRemoveRole = (index) => {
  attrs.value.splice(index, 1);
  manyFormValidate.value.splice(index, 1);
};

// 删除属性
const handleRemove2 = (item, index) => {
  item.splice(index, 1);
};

// 添加规则名称
const createAttrName = () => {
  if (formDynamic.value.attrsName && formDynamic.value.attrsVal) {
    let data = {
      value: formDynamic.value.attrsName,
      detail: [formDynamic.value.attrsVal]
    };
    // console.log('data', data);
    attrs.value.push(data);
    var hash = {};
    // console.log('this.attrs',this.attrs);
    attrs.value = attrs.value.reduce(function (item, next) {
      hash[next.value] ? '' : (hash[next.value] = true && item.push(next));
      return item;
    }, []);
    clearAttr();
    showInput.value = false;
    createBtn.value = true;
  } else {
    proxy?.$modal.msgError('请添加完整的规格！');
  }
};
// 添加属性
const createAttr = (num, idx) => {
  if (num) {
    attrs.value[idx].detail.push(num);
    var hash = {};
    // console.log('this.attrs[idx].detail',attrs[idx].detail);
    attrs.value[idx].detail = attrs.value[idx].detail.reduce(function (item, next) {
      hash[next] ? '' : (hash[next] = true && item.push(next));
      return item;
    }, []);
  } else {
    proxy?.$modal.msgError('请添加属性！');
  }
};

// 删除表格中的属性
const delAttrTable = (index) => {
  manyFormValidate.value.splice(index, 1);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();

  attrs.value = [];
  form.value.header = [];
  manyFormValidate.value = [];
  oneFormValidate.value = [
    {
      price: 0,
      otPrice: 0,
      stock: 9999
    }
  ];
  getProductTypeChildList();
  dialog.visible = true;
  dialog.title = '添加商品';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductVO) => {
  reset();
  attrs.value = [];
  form.value.header = [];
  manyFormValidate.value = [];
  oneFormValidate.value = [
    {
      price: 0,
      otPrice: 0,
      stock: 9999
    }
  ];
  getProductTypeChildList();
  const _id = row?.id || ids.value[0];
  const res = await getProduct(_id);
  Object.assign(form.value, res.data);

  console.log(' that.form.rule', form.value.rule);
  if (form.value.rule !== null && form.value.rule !== undefined) {
    console.log(' that.form.rule 111', form.value.rule);
    attrs.value = form.value.rule.ruleValueArray;
  }
  splits.value = res.data.splits;
  form.value.header = [];
  console.log('that.form.specType', form.value.specType);
  if (form.value.specType === 0) {
    //单规格
    manyFormValidate.value = [];
    console.log('response.data.productValue["默认"]', res.data.productValue['默认']);
    oneFormValidate.value[0] = res.data.productValue['默认'];
    console.log('oneFormValidate', oneFormValidate.value);
    // if (res.data.productValue != undefined && res.data.productValue.length > 0){
    // } else {
    //   oneFormValidate.value = [
    //     {
    //       price: 0,
    //       otPrice: 0,
    //       stock: 9999
    //     }
    //   ];
    // }
  } else {
    //多规格
    createBtn.value = true;
    console.log('that.manyFormValidate', manyFormValidate.value);
    that.generate(0);
  }

  getRuleList(form.value.ruleId);

  dialog.visible = true;
  dialog.title = '修改商品';
};

/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      if (form.value.image === undefined) {
        proxy?.$modal.msgError('请上传预览图片');
      }
      if (form.value.sliderImage === undefined) {
        proxy?.$modal.msgError('请上传轮播图');
      }

      if (form.value.specType === 0) {
        form.value.attrs = oneFormValidate.value;
        form.value.header = [];
        form.value.items = [];
      } else {
        form.value.items = attrs.value;
        form.value.attrs = manyFormValidate.value;
      }
      if (form.value.specType === 1 && manyFormValidate.value.length == 0) {
        proxy?.$modal.msgError('请点击生成规格');
      }

      if (form.value.id) {
        await updateProduct(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProduct(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delProduct(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'shopping/product/export',
    {
      ...queryParams.value
    },
    `product_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getRuleList(0);
});
</script>

<style lang="scss" scoped>
.product-view {
  width: 100%;
  position: relative;
  overflow: hidden;

  .product-edit-view {
    box-shadow: 2px 2px 6px rgb(0 21 41 / 35%);
    padding: 20px;
  }

  .product-edit-view .el-scrollbar {
    height: calc(100vh - 12.5rem);
  }
  .scrollbar-wrapper {
    overflow-x: hidden !important;
  }
}
</style>
